<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-select v-model="query.display" placeholder="显示状态" class="handle-select mr10">
                    <el-option key="1" label="显示" :value="+1"></el-option>
                    <el-option key="2" label="隐藏" :value="+2"></el-option>
                </el-select>
                <el-input v-model="query.title" placeholder="标题" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="handleReset">重置</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="title" label="标题" show-overflow-tooltip min-width="180" align="center"></el-table-column>
                <el-table-column prop="content" label="内容" show-overflow-tooltip min-width="180" align="center"></el-table-column>
                <el-table-column prop="modulename" label="所属模块" width="120" align="center"></el-table-column>
                <!-- <el-table-column label="审核状态" @row-click="scope(scope)" width="80" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ +scope.row.status === 0 ? '已通过' : '不通过' }}</template>
                </el-table-column>-->
                <el-table-column
                    prop="user[0].username"
                    label="创建人"
                    show-overflow-tooltip
                    min-width="120"
                    align="center"
                ></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
                <el-table-column label="显示状态" @row-click="scope(scope)" width="80" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ +scope.row.display === 1 ? '显示' : '隐藏' }}</template>
                </el-table-column>
                <el-table-column prop="readNum" label="浏览次数" width="80" align="center"></el-table-column>
                <el-table-column label="点赞次数" @row-click="scope(scope)" width="80" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ scope.row.likeList.length }}</template>
                </el-table-column>
                <el-table-column label="被举报次数" @row-click="scope(scope)" width="100" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ scope.row.reportList.length }}</template>
                </el-table-column>
                <el-table-column label="操作" width="50" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <span>
                                <i class="el-icon-lx-more"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item>
                                    <el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                </el-dropdown-item>
                                <el-dropdown-item>
                                    <el-button type="text" @click="toDetail(scope.$index, scope.row)">查看详情</el-button>
                                </el-dropdown-item>
                                <el-dropdown-item>
                                    <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="120px" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="显示状态" prop="display">
                    <el-radio v-model="form.display" :label="+1">显示</el-radio>
                    <el-radio v-model="form.display" :label="+2">隐藏</el-radio>
                </el-form-item>
                <el-form-item label="浏览次数" prop="readNum">
                    <el-input v-model="form.readNum"></el-input>
                </el-form-item>
                <el-form-item label="所属模块" prop="modulename">
                    <el-select v-model="form.modulename" placeholder="所属模块" class="handle-select mr10">
                        <el-option
                            :label="item.modulename"
                            :value="item.modulename"
                            v-for="(item, index) in modelList"
                            :key="index"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit(form)">取 消</el-button>
                <el-button type="primary" @click="saveEdit(form)">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 查看详情抽屉 -->
        <el-drawer :title="form.title" :visible.sync="detailDrawer" size="50%">
            <div slot="title" class="drawerTitle">
                <div>
                    {{ form.title }} <el-tag size="mini">{{ form.modulename }}</el-tag>
                </div>
                <div>
                    <el-button type="success" @click="innerDrawer = true">评论列表</el-button>
                    <!-- <el-button type="success" @click="innerDrawer2 = true">点赞列表</el-button> -->
                </div>
            </div>
            <div class="drawerContentWrap">
                <!-- <div v-html="form.content"></div> -->
                <div class="ql-container">
                    <div v-if="form.content" class="ql-editor" v-html="form.content"></div>
                </div>
                <div class="drawerFoot">
                    <p v-if="form.user">创建人：{{ form.user[0].username }}</p>
                    <p>浏览次数：{{ form.readNum }} 次</p>
                    <p v-if="form.reportList">
                        被举报次数：<span>{{ form.reportList.length }}</span> 次
                    </p>
                    <p>{{ form.createTime }}</p>
                </div>
                <el-drawer title="评论列表" :append-to-body="true" :visible.sync="innerDrawer" class="innerDrawer1">
                    <div slot="title">
                        <div v-if="form.commentList">评论列表 | {{ form.commentList.length }}条</div>
                    </div>
                    <div class="com_wrap" v-for="(item, index) in form.commentList" :key="index">
                        <div class="com_pic" v-if="item.user">
                            <img :src="item.user[0].headPic.content" alt="" />
                        </div>
                        <div class="com_content">
                            <div v-if="item.user">{{ item.user[0].username }}</div>
                            <div class="com_content2">
                                <span v-if="item.content">{{ item.content }}</span>
                                <span v-else>[该评论已被删除]</span>
                            </div>
                            <div class="com_content3">
                                <span>{{ item.createTime }}</span>
                                <span @click="deleteComment(item, index)" class="shanchu" v-if="item.content">删除</span>
                            </div>
                        </div>
                    </div>
                </el-drawer>
                <el-drawer title="点赞列表" :append-to-body="true" :visible.sync="innerDrawer2" class="innerDrawer1">
                    <div slot="title">
                        <div v-if="form.likeList">点赞列表 | {{ form.likeList.length }}条</div>
                    </div>
                    <div class="com_wrap" v-for="(item, index) in form.likeList" :key="index">
                        <div class="com_pic" v-if="item.user">
                            <img :src="item.user[0].headPic.content" alt="" />
                        </div>
                        <div class="com_content" v-if="item.user">
                            <div>{{ item.user[0].username }}</div>
                            <div class="com_content2">{{ item.content }}</div>
                            <div class="com_content3">{{ item.createTime }}</div>
                        </div>
                    </div>
                </el-drawer>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { fetchData } from '../../../api/index';
import { getPost, setPost, removePost, getModule, deletePostcomment } from '@/views/api/api.js';
export default {
    name: 'postManagement',
    data() {
        return {
            query: {
                display: '',
                title: '',
                pageIndex: 1,
                pageSize: 10
            },
            detailDrawer: false,
            innerDrawer: false,
            oldCommentList: [],
            innerDrawer2: false,
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            modelList: [],
            rules: {
                username: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
                password: [{ required: true, message: '密码不能为空！', trigger: 'blur' }],
                phone: [{ required: true, message: '手机号码不能为空！', trigger: 'blur' }],
                college: [{ required: true, message: '学院不能为空！', trigger: 'blur' }],
                role: [{ required: true, message: '角色不能为空！', trigger: 'blur' }],
                sex: [{ required: true, message: '性别不能为空！', trigger: 'blur' }],
                status: [{ required: true, message: '审核状态不能为空！', trigger: 'blur' }],
                email: [{ required: true, message: '邮箱不能为空！', trigger: 'blur' }],
                safetyProblem1: [{ required: true, message: '安全问题1不能为空！', trigger: 'blur' }],
                safetyAnswer1: [{ required: true, message: '安全问题答案1不能为空！', trigger: 'blur' }],
                safetyProblem2: [{ required: true, message: '安全问题2不能为空！', trigger: 'blur' }],
                safetyAnswer2: [{ required: true, message: '安全问题答案2不能为空！', trigger: 'blur' }]
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取所有的数据
        getData() {
            getPost(this.query).then(res => {
                if (!res.data.code) {
                    // 成功
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    for (let j = 0; j < this.tableData.length; j++) {
                        this.tableData[j].createTime = this.utc2beijing(this.tableData[j].createTime);
                    }
                } else {
                    // 失败
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 触发重置按钮
        handleReset() {
            this.query = {
                display: '',
                title: '',
                pageIndex: 1,
                pageSize: 10
            };
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.multipleSelection = [];
                    this.multipleSelection.push(row._id);
                    let params = {
                        multipleSelection: this.multipleSelection
                    };
                    removePost(params).then(res => {
                        if (res.data.code) {
                            // Toast.fail(res.data.msg)
                        } else {
                            this.$message.success('删除成功');
                            this.getData();
                            this.multipleSelection = [];
                        }
                    });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = [];
            for (let i = 0; i < val.length; i++) {
                this.multipleSelection.push(val[i]._id);
            }
        },
        // 查看详情操作
        toDetail(index, row) {
            this.detailDrawer = true;
            this.form = JSON.parse(JSON.stringify(row));
            this.oldCommentList = JSON.parse(JSON.stringify(this.form.commentList));
            for (let i = 0; i < this.form.commentList.length; i++) {
                this.form.commentList[i].createTime = this.utc2beijing(this.form.commentList[i].createTime);
            }
        },
        delAllSelection() {
            // 二次确认删除
            if (this.multipleSelection.length > 0) {
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        let params = {
                            multipleSelection: this.multipleSelection
                        };
                        removePost(params).then(res => {
                            if (res.data.code) {
                                // Toast.fail(res.data.msg)
                            } else {
                                this.$message.success('删除成功');
                                this.getData();
                                this.multipleSelection = [];
                            }
                        });
                    })
                    .catch(() => {});
            } else {
                this.$message.warning('请选择要删除的用户');
            }
        },
        getMoudel() {
            // 初始化，从数据库中获取所有的模块名称
            getModule().then(res => {
                if (res.data.code) {
                    // Toast.fail(res.data.msg)
                } else {
                    this.modelList = res.data.Info;
                }
            });
        },
        // 编辑操作
        handleEdit(index, row) {
            this.getMoudel();
            this.idx = index;
            this.form = JSON.parse(JSON.stringify(row));
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit(form) {
            this.$refs.form.validate(valid => {
                if (valid) {
                    let params = {
                        id: this.form._id,
                        title: this.form.title,
                        content: this.form.content,
                        display: this.form.display,
                        readNum: this.form.readNum,
                        modulename: this.form.modulename
                    };
                    setPost(params).then(res => {
                        if (res.data.code) {
                            this.$message({
                                showClose: true,
                                message: res.data.msg,
                                type: 'error'
                            });
                        } else {
                            this.editVisible = false;
                            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                            this.$set(this.tableData, this.idx, this.form);
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        cancelEdit(form) {
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        scope(scope) {
            console.log(scope);
        },
        // 时间戳转为时间
        timestampToTime(timestamp) {
            var date = new Date(timestamp); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '年';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日 ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return Y + M + D + h + m + s;
        },
        // UTC时间格式转通用格式时间
        // eslint-disable-next-line camelcase
        utc2beijing(utc_datetime) {
            // 转为正常的时间格式 年-月-日 时:分:秒
            // eslint-disable-next-line camelcase
            var T_pos = utc_datetime.indexOf('T');
            // eslint-disable-next-line camelcase
            var Z_pos = utc_datetime.indexOf('Z');
            // eslint-disable-next-line camelcase
            var year_month_day = utc_datetime.substr(0, T_pos);
            // eslint-disable-next-line camelcase
            var hour_minute_second = utc_datetime.substr(
                // eslint-disable-next-line camelcase
                T_pos + 1,
                // eslint-disable-next-line camelcase
                Z_pos - T_pos - 1
            );
            // eslint-disable-next-line camelcase
            var new_datetime = year_month_day + ' ' + hour_minute_second; // 2017-03-31 08:02:06

            // 处理成为时间戳
            // eslint-disable-next-line no-use-before-define
            timestamp = new Date(Date.parse(new_datetime));
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp.getTime();
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp / 1000;

            // 增加8个小时，北京时间比utc时间多八个时区
            // eslint-disable-next-line no-use-before-define
            var timestamp = timestamp + 8 * 60 * 60;

            // 时间戳转为时间
            // eslint-disable-next-line camelcase
            var beijing_datetime = this.timestampToTime(timestamp * 1000);
            // eslint-disable-next-line camelcase
            return beijing_datetime; // 2017-03-31 16:02:06
        },
        // 删除评论
        deleteComment(item, index) {
            this.$confirm('删除评论后相关数据将无法找回，您确定删除该评论吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    let param = {
                        id: this.form._id,
                        createTime: this.oldCommentList[index].createTime
                    };
                    deletePostcomment(param).then(res => {
                        if (res.data.code) {
                            //   Toast.fail(res.data.msg)
                        } else {
                            this.form.commentList[index].content=''
                            this.$set(this.form);
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            });
                        }
                    });
                })
                .catch(() => {});
        }
    }
};
</script>
<style>
.innerDrawer1 .el-drawer__body {
    overflow: auto;
}
</style>
<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.drawerFoot {
    color: #72767b;
    text-align: right;
    font-size: 14px;
    margin-top: 20px;
}
.drawerContentWrap {
    padding: 0 20px 20px 20px;
}
.drawerTitle {
    display: flex;
    justify-content: space-between;
}
.com_wrap {
    display: flex;
    padding: 0 20px 20px 20px;
}
.com_pic {
    width: 50px;
    height: 50px;
}
.com_wrap img {
    width: 100%;
    border-radius: 50%;
}
.com_content {
    margin-left: 10px;
}
.innerDrawer {
    overflow: auto;
}
.com_content2 {
    margin: 10px 0;
}
.com_content3 {
    color: #b5b8c2;
}
.shanchu {
    color: red;
    margin-left: 10px;
}
</style>
